import React, { Component } from "react";
import { connect } from "react-redux";

import {
    createIncrementAction,
    createDecrementAction,
    createIncrementAsyncAction,
} from "../../redux/actions/count";

/**
 * 负责展示数据的UI组件
 */
class Count extends Component {
    increment = () => {
        const number = parseInt(this.selectNumber.value);

        this.props.increment(number);
    };

    decrement = () => {
        const number = parseInt(this.selectNumber.value);

        this.props.decrement(number);
    };

    incrementIfOdd = () => {
        const { count } = this.props;
        if (count % 2 === 1) {
            const number = parseInt(this.selectNumber.value);

            this.props.increment(number);
        }
    };

    incrementAsync = () => {
        const number = parseInt(this.selectNumber.value);
        this.props.incrementAsync(number, 500);
    };

    render() {
        const { count, peopleCount } = this.props;

        return (
            <div>
                <h2>Count组件，下方组件人数为：{peopleCount}</h2>
                <h4>当前求和为：{count}</h4>
                <select ref={(c) => (this.selectNumber = c)}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                &nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOdd}>
                    当前求和为奇数时相加
                </button>
                &nbsp;
                <button onClick={this.incrementAsync}>异步加</button>
            </div>
        );
    }
}

/**
 * 负责与redux通信的容器组件
 */
// mapStateToProps函数的返回值会作为状态传入UI组件的props中
const mapStateToProps = (state) => ({
    count: state.count,
    peopleCount: state.people.length,
});

// mapDispatchToProps函数的返回值作为操作状态的方法函数传入UI组件的props中
// const mapDispatchToProps = (dispatch) => ({
//     increment: (number) => {
//         dispatch(createIncrementAction(number));
//     },
//     decrement: (number) => {
//         dispatch(createDecrementAction(number));
//     },
//     incrementAsync: (number, time) => {
//         dispatch(createIncrementAsyncAction(number, time));
//     },
// });

// mapDispatchToProps也可以是一个只包含创建对应action creators的对象，react-redux会自动调用dispatch
const mapDispatchToProps = {
    increment: createIncrementAction,
    decrement: createDecrementAction,
    incrementAsync: createIncrementAsyncAction,
};

// 创建并暴露一个Count的容器组件
export default connect(mapStateToProps, mapDispatchToProps)(Count);
